class Snake {
  constructor(width = 20, heigh = 20, directives = 'right') {
    this.elements = []
    this.width = width
    this.heigh = heigh
    this.directives = directives

    this.body = [{
        x: 3,
        y: 2,
        color: 'red'
      },
      {
        x: 2,
        y: 2,
        color: 'blue'
      },
      {
        x: 1,
        y: 2,
        color: 'blue'
      },
    ]
  }
  render(map) {
    this.removesnake()
    this.addsnake(map)
  }
  move(food, map) {
    for (let i = this.body.length - 1; i > 0; i--) {
      this.body[i].x = this.body[i - 1].x
      this.body[i].y = this.body[i - 1].y
    }
    let head = this.body[0]
    // 移动的方向
    switch (this.directives) {
      case 'right':
        head.x += 1
        break
      case 'left':
        head.x -= 1
        break
      case 'top':
        head.y -= 1
        break
      case 'bottom':
        head.y += 1
        break
    }
    // 吃到食物
    if (food.x == head.x && food.y == head.y) {
      let last = this.body[this.body.length - 1]
      this.body.push({
        x: last.x,
        y: last.y,
        color: last.color
      })
      food.render(map)
    }
  }
  addsnake(map) {
    for (let i = 0; i < this.body.length; i++) {
      let object = this.body[i]
      let snake = document.createElement('div')
      map.appendChild(snake)
      this.elements.push(snake)
      // 设置snake样式
      snake.style.position = 'absolute'
      snake.style.top = object.y * this.heigh + 'px'
      snake.style.width = this.width + 'px'
      snake.style.height = this.heigh + 'px'
      snake.style.left = object.x * this.width + 'px'
      snake.style.backgroundColor = object.color
    }
  }

  removesnake() {
    for (let i = this.elements.length - 1; i >= 0; i--) {
      this.elements[i].parentNode.removeChild(this.elements[i])
      this.elements.splice(i, 1)
    }
  }
}

export default Snake